﻿using System;
using System.Collections.Generic;
using System.Linq;
using DataLayer;
using Common;
using Common.DTO;

namespace LogicLayer
{
    public class PlayerHandler
    {
        // --- INFO ---

        public static bool CheckIfPlayerWithUsernameExists(string username)
        {
            var repository = new RepositoryBase();
            var existingPlayer = repository.GetEntitiesWhere<PlayerEntity>(x =>
                                                                            x.Name == username).FirstOrDefault();
            if (existingPlayer != null)
            {
                return true;
            }

            return false;
        }

        public static List<Player> GetPlayerList()
        {
            var repository = new RepositoryBase();

            var players = repository.GetAll<PlayerEntity>();
            return Factory.CreateListOfPlayers(players);
        }

        // --- ACTIONS ---

        public static bool CreatePlayer(string username, string password, string email)
        {
            var repository = new RepositoryBase();
            var existingPlayer = repository.GetEntitiesWhere<PlayerEntity>(x => 
                                                                            x.Name == username || 
                                                                            x.Mail == email).FirstOrDefault();
            if (existingPlayer != null)
            {
                return false;
            }

            var player = new PlayerEntity 
            { 
                Name = username,
                Password = password,
                Mail = email
            };

            return repository.Save<PlayerEntity>(player);
        }

        public static Player LoginPlayer(string username, string password)
        {
            PlayerEntity player;
            try
            {
                var repository = new RepositoryBase();
                player = repository.GetEntitiesWhere<PlayerEntity>(x =>
                                                                x.Name == username &&
                                                                x.Password == password).First();
            }
            catch (Exception)
            {
                return null;
            }

            return Factory.CreatePlayer(player);
        }

        private static void CreateToken(int playerId)
        { 
            
        }

        
    }
}
